package com.hnust.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Component
@Slf4j
public class CleveroomMessage extends TextWebSocketHandler {
    /**
     * socket 建立成功事件
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        Object token = session.getAttributes().get("token");
        if (token != null) {
            // 用户连接成功，放入在线用户缓存
            WsSessionManager.add(token.toString(), session);
        } else {
            throw new RuntimeException("用户登录已经失效!");
        }
    }
    /**
     * 接收消息事件
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        Object token = session.getAttributes().get("token");
        String content="服务端收到了用户"+token+"的信息："+payload;
        log.info(content);
        session.sendMessage(new TextMessage(content));
    }

    /**
     * socket 断开连接时
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        Object token = session.getAttributes().get("token");
        if (token != null) {
            // 用户退出，移除缓存
            WsSessionManager.remove(token.toString());
        }
    }

    /**
     * 向所有用户发送消息
     */
    public void sendAllMessage(String message) {
        try{
            for(String key:WsSessionManager.SESSION_POOL.keySet()){
                WsSessionManager.get(key).sendMessage(new TextMessage(
                        message
                ));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    /**
     * 发送单点消息
     */
    public void sendMessageByKey(String key,String message) {
        try{
            WsSessionManager.get(key).sendMessage(new TextMessage(
                    message
            ));
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
